package org.zjx.window;

import com.sun.jna.platform.win32.WinDef;
import org.zjx.analyse.ScreenshotAnalyse;
import org.zjx.analyse.action.StartWindowAction;
import org.zjx.common.entity.Rect;
import org.zjx.core.GameThread;
import org.zjx.log.LogLevel;
import org.zjx.log.Logger;
import org.zjx.resolution.resolution.StartWindowResolution;
import org.zjx.resource.IBaseConfig;
import org.zjx.resource.ResourceManager;
import org.zjx.util.HwndUtil;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class WindowManager {
    private final Logger logger = Logger.getLogger();
    private final List<GameThread> gameThreads = new ArrayList<>();


    public WindowManager(IBaseConfig baseConfig) {
        ResourceManager.CONFIG = baseConfig;
        ExecutorService executor = Executors.newFixedThreadPool(baseConfig.gameThreadSize());
        List<Rect> windowRects = getWindowRects();
        for (int i = 0; i < baseConfig.gameThreadSize(); i++) {
            GameThread gameThread = new GameThread(new Point(windowRects.get(i).getLeft(), windowRects.get(i).getTop()), this);
            gameThreads.add(gameThread);
            executor.execute(gameThread);
        }
    }

    public List<Rect> getWindowRects() {
        int totalWindows = ResourceManager.CONFIG.gameThreadSize(); // 假设需要排列6个窗口

        List<Rect> windowRects;
        if (ResourceManager.CONFIG.gameThreadSize() == 1) {
            windowRects = Collections.singletonList(new Rect(0, 0, ResourceManager.CONFIG.getWindowSize().x, ResourceManager.CONFIG.getWindowSize().y));
        } else {
            windowRects = WindowLayoutHelper.calculateWindowPositions(totalWindows, ResourceManager.CONFIG.getWindowSize());
        }
        return windowRects;
    }


    public synchronized void launchGame(GameThread gameThread) {
        boolean lock = GlobalLockWithTimeout.tryLock(10, TimeUnit.MILLISECONDS);
        while (!lock) {
            lock = GlobalLockWithTimeout.tryLock();
        }
        try {
            while (true) {
                logger.log("GameModule", LogLevel.INFO, "循环");
                List<WinDef.HWND> launchWindows = HwndUtil.getHwndS(null, "launch");
                if (launchWindows.isEmpty()) launchWindows = HwndUtil.getHwndS("#32770", "梦幻西游 ONLINE");

                for (WinDef.HWND hwnd : launchWindows) {
                    launchGame(hwnd);
                    logger.log("GameModule", LogLevel.INFO, "找到lunch");
                    while (awaitNewWindow("WSGAME", null) == null) {
                        delay(500);
                    }
                    delay(1000);
                }
                WinDef.HWND hwnd = awaitNewWindow("WSGAME", null);
                if (hwnd == null) {
                    openGame();
                    logger.log("GameModule", LogLevel.INFO, "等待lunch");
                    while (awaitNewWindow(null, "launch") == null && awaitNewWindow(null, "梦幻西游 ONLINE") == null) {
                        delay(1000);
                    }
                } else {
                    logger.log("GameModule", LogLevel.INFO, "launchGame成功");
                    gameThread.getWindow().init(hwnd, GameWindow.WINDOW_STATUS_LOGIN);
                    break;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            GlobalLockWithTimeout.unlock();
        }
    }

    //执行launch界面的登录按钮
    public void launchGame(WinDef.HWND hwnd) {

        GameWindow gameWindow = new GameWindow(new Point(200, 200));
        gameWindow.init(hwnd, GameWindow.WINDOW_STATUS_START);

        StartWindowAction action = new StartWindowAction(new ScreenshotAnalyse(gameWindow));

        while (action.isOpened()) {
            gameWindow.flush();
            boolean startButton = action.clickButton(StartWindowResolution.START_WINDOW_START_BUTTON_RECT);

            gameWindow.delay(1000);
        }
        delay(1000);
    }

    public WinDef.HWND awaitNewWindow(String className, String title) {
        List<WinDef.HWND> haves = new ArrayList<>();
        for (GameThread gameThread : gameThreads) {
            if (gameThread.getWindow() != null) haves.add(gameThread.getWindow().getHwnd());
        }

        List<WinDef.HWND> launchWindows = HwndUtil.getHwndS(className, title);
        for (WinDef.HWND hwnd : launchWindows) {
            boolean bestowed = false;
            for (WinDef.HWND hwnd1 : haves) {
                if (hwnd.equals(hwnd1)) {
                    bestowed = true;
                    break;
                }
            }
            if (!bestowed) {
                return hwnd;
            }
        }
        return null;
    }

    public void delay(int delay) {
        try {
            // 使用TimeUnit更清晰地表达等待时间
            TimeUnit.MILLISECONDS.sleep(delay);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.log("GameModule", LogLevel.INFO, "等待被中断");
        }
    }


    public void openGame() throws IOException {
        // 设置快捷方式文件路径
        File shortcutFile = new File(ResourceManager.CONFIG.gameInkPath());
        // 检查当前平台是否支持桌面操作
        if (Desktop.isDesktopSupported()) {
            Desktop desktop = Desktop.getDesktop();
            // 打开快捷方式文件
            desktop.open(shortcutFile);
            logger.log("GameModule", LogLevel.INFO, "快捷方式已启动");
        } else {
            logger.log("GameModule", LogLevel.INFO, "桌面操作不被当前平台支持");
        }
    }
}
